from importlib import import_module
from typing import Type, Any, Dict, Optional, TYPE_CHECKING

if TYPE_CHECKING:
    from qtorch.core.interfaces import (
        IModuleLifecycle,
        IHotSwap,
        IDataProvider,
        IStrategy,
        IRiskManager
    )
else:
    IModuleLifecycle = object
    IHotSwap = object
    IDataProvider = object
    IStrategy = object
    IRiskManager = object
if TYPE_CHECKING:
    from qtorch.core.interfaces import IModuleLifecycle, IHotSwap, IDataProvider, IStrategy, IRiskManager
else:
    IModuleLifecycle = object
    IHotSwap = object
    IDataProvider = object
    IStrategy = object
    IRiskManager = object

class DIContainer:
    """依赖注入容器"""
    
    def __init__(self):
        self._registry: Dict[Type, Any] = {}
        self._lifecycle_managed: Dict[Type, IModuleLifecycle] = {}
        self._hot_swap_ready: Dict[Type, IHotSwap] = {}

    def register(self, interface: Type, implementation: Any) -> None:
        """注册接口实现"""
        if not isinstance(implementation, interface):
            raise TypeError(f"{implementation} must implement {interface.__name__}")
        
        # 注册实现
        self._registry[interface] = implementation
        
        # 检查并注册生命周期管理
        if isinstance(implementation, IModuleLifecycle):
            self._lifecycle_managed[interface] = implementation
        
        # 检查并注册热插拔支持
        if isinstance(implementation, IHotSwap):
            self._hot_swap_ready[interface] = implementation

    def resolve(self, interface: Type) -> Any:
        """解析接口实现"""
        impl = self._registry.get(interface)
        if not impl:
            raise ValueError(f"No implementation registered for {interface.__name__}")
        return impl

    def register_data_provider(self, provider: 'IDataProvider') -> None:
        """注册数据提供者"""
        from qtorch.core.interfaces import IDataProvider
        self.register(IDataProvider, provider)

    def register_strategy(self, strategy: 'IStrategy') -> None:
        """注册策略"""
        from qtorch.core.interfaces import IStrategy
        self.register(IStrategy, strategy)

    def initialize_all(self) -> None:
        """初始化所有注册的模块"""
        for module in self._lifecycle_managed.values():
            module.initialize()

    def shutdown_all(self) -> None:
        """关闭所有注册的模块"""
        for module in self._lifecycle_managed.values():
            module.shutdown()

    def hot_swap(self, interface: Type, new_impl: Any) -> None:
        """热插拔模块实现"""
        if interface not in self._hot_swap_ready:
            raise ValueError(f"Module {interface.__name__} does not support hot swapping")
        
        # 验证新实现
        if not isinstance(new_impl, interface):
            raise TypeError(f"New implementation must implement {interface.__name__}")
        
        # 执行热插拔
        self._hot_swap_ready[interface].swap(new_impl)
        self._registry[interface] = new_impl

    def register_risk_manager(self, risk_manager: 'IRiskManager') -> None:
        """注册风险管理"""
        from qtorch.core.interfaces import IRiskManager
        self.register(IRiskManager, risk_manager)